﻿@*
    添加过程检验页面
*@
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>添加过程检验</title>
    <link href="~/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
    <style>
        .layui-form {
            padding: 20px;
            max-width: 800px;
            margin: 0 auto;
        }
        .layui-form-label {
            width: 120px;
        }
        .layui-input-block {
            margin-left: 150px;
        }
        .form-buttons {
            text-align: center;
            margin-top: 30px;
        }
        .required::before {
            content: '* ';
            color: red;
        }
    </style>
</head>
<body>
    <div class="layui-container">
        <div class="layui-card">
            <div class="layui-card-header">
                <h2>添加过程检验</h2>
            </div>
            <div class="layui-card-body">
                @Html.AntiForgeryToken()
                <form class="layui-form" lay-filter="processForm">
                    <div class="layui-form-item">
                        <label class="layui-form-label required">检验单编号</label>
                        <div class="layui-input-block">
                            <div style="display: flex; align-items: center; gap: 10px;">
                                <input type="text" name="ProcessCode" lay-verify="required" placeholder="请输入检验单编号" autocomplete="off" class="layui-input" style="flex: 1;">
                                <input type="checkbox" name="autoGenerate" lay-filter="autoGenerate" lay-skin="switch" lay-text="自动生成|手动输入" title="自动生成">
                            </div>
                        </div>
                    </div>
                    
                    <div class="layui-form-item">
                        <label class="layui-form-label required">检验类型</label>
                        <div class="layui-input-block">
                            <select name="ProcessType" lay-verify="required">
                                <option value="">请选择检验类型</option>
                                <option value="首件检验">首件检验</option>
                                <option value="过程检验">过程检验</option>
                                <option value="末件检验">末件检验</option>
                                <option value="巡回检验">巡回检验</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="layui-form-item">
                        <label class="layui-form-label required">工单编号</label>
                        <div class="layui-input-block">
                            <div style="position: relative;">
                                <input type="text" name="OrderCode" lay-verify="required" placeholder="请输入工单编号" autocomplete="off" class="layui-input">
                                <i class="layui-icon layui-icon-search" style="position: absolute; right: 10px; top: 50%; transform: translateY(-50%); cursor: pointer; color: #999;" onclick="selectWorkOrder()" title="选择工单"></i>
                            </div>
                        </div>
                    </div>
                    
                    <div class="layui-form-item">
                        <label class="layui-form-label required">工作站编码</label>
                        <div class="layui-input-block">
                            <div style="position: relative;">
                                <input type="text" name="WorkStationCode" lay-verify="required" placeholder="请输入工作站编码" autocomplete="off" class="layui-input">
                                <i class="layui-icon layui-icon-search" style="position: absolute; right: 10px; top: 50%; transform: translateY(-50%); cursor: pointer; color: #999;" onclick="selectWorkStation()" title="选择工作站"></i>
                            </div>
                        </div>
                    </div>
                    
                    <div class="layui-form-item">
                        <label class="layui-form-label">工作站名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="WorkStationName" placeholder="请输入工作站名称" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    
                    <div class="layui-form-item">
                        <label class="layui-form-label required">产品物料编码</label>
                        <div class="layui-input-block">
                            <input type="text" name="ProductCode" lay-verify="required" placeholder="请输入产品物料编码" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    
                    <div class="layui-form-item">
                        <label class="layui-form-label required">产品物料名称</label>
                        <div class="layui-input-block">
                            <input type="text" name="ProductName" lay-verify="required" placeholder="请输入产品物料名称" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    
                    <div class="layui-form-item">
                        <label class="layui-form-label">规格型号</label>
                        <div class="layui-input-block">
                            <input type="text" name="Specifications" placeholder="请输入规格型号" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    
                    <div class="layui-form-item">
                        <label class="layui-form-label">单位</label>
                        <div class="layui-input-block">
                            <input type="text" name="Unitt" placeholder="请输入单位" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    
                    <div class="layui-form-item">
                        <label class="layui-form-label required">检测数量</label>
                        <div class="layui-input-block">
                            <input type="number" name="TestingNum" lay-verify="required|number" placeholder="请输入检测数量" autocomplete="off" class="layui-input" min="1">
                        </div>
                    </div>
                    
                    <div class="layui-form-item">
                        <label class="layui-form-label required">检测日期</label>
                        <div class="layui-input-block">
                            <input type="text" name="TestingDate" id="testingDate" lay-verify="required" placeholder="请选择检测日期" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    
                    <div class="layui-form-item">
                        <label class="layui-form-label required">检测结果</label>
                        <div class="layui-input-block">
                            <select name="TestingResult" lay-verify="required">
                                <option value="">请选择检测结果</option>
                                <option value="合格">合格</option>
                                <option value="不合格">不合格</option>
                                <option value="待复检">待复检</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="layui-form-item">
                        <label class="layui-form-label required">检测人员</label>
                        <div class="layui-input-block">
                            <input type="text" name="TestingPerson" lay-verify="required" placeholder="请输入检测人员" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    
                    <div class="layui-form-item">
                        <label class="layui-form-label">单据状态</label>
                        <div class="layui-input-block">
                            <select name="State">
                                <option value="0" selected>草稿</option>
                                <option value="1">已提交</option>
                                <option value="2">已审核</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="form-buttons">
                        <button type="submit" class="layui-btn" lay-submit lay-filter="submitForm">
                            <i class="layui-icon layui-icon-ok"></i>保存
                        </button>
                        <button type="reset" class="layui-btn layui-btn-primary">
                            <i class="layui-icon layui-icon-refresh"></i>重置
                        </button>
                        <button type="button" class="layui-btn layui-btn-warm" onclick="window.history.back()">
                            <i class="layui-icon layui-icon-return"></i>返回
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 工作站选择弹出框 -->
    <div id="workStationDialog" style="display: none; padding: 20px;">
        <div class="layui-form" lay-filter="workStationSearchForm">
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">工作站编号</label>
                    <div class="layui-input-inline">
                        <input type="text" name="searchWorkStationCode" class="layui-input" placeholder="请输入工作站编号">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">所属工序</label>
                    <div class="layui-input-inline">
                        <input type="text" name="searchProcessBelongs" class="layui-input" placeholder="请输入所属工序">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">所在车间</label>
                    <div class="layui-input-inline">
                        <input type="text" name="searchWorkshop" class="layui-input" placeholder="请输入所在车间">
                    </div>
                </div>
                <div class="layui-inline">
                    <button type="button" class="layui-btn" id="searchWorkStationBtn">
                        <i class="layui-icon layui-icon-search"></i> 搜索
                    </button>
                    <button type="button" class="layui-btn layui-btn-primary" id="resetWorkStationBtn">
                        <i class="layui-icon layui-icon-refresh"></i> 重置
                    </button>
                </div>
            </div>
        </div>
        <table id="workStationTable" lay-filter="workStationTable"></table>
    </div>

    <!-- 工单选择弹出框 -->
    <div id="workOrderDialog" style="display: none; padding: 20px;">
        <div class="layui-form" lay-filter="workOrderSearchForm">
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label">工单编码</label>
                    <div class="layui-input-inline">
                        <input type="text" name="searchWorkOrderCode" class="layui-input" placeholder="请输入工单编码">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">工单名称</label>
                    <div class="layui-input-inline">
                        <input type="text" name="searchWorkOrderName" class="layui-input" placeholder="请输入工单名称">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">产品编号</label>
                    <div class="layui-input-inline">
                        <input type="text" name="searchProductCode" class="layui-input" placeholder="请输入产品编号">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">产品名称</label>
                    <div class="layui-input-inline">
                        <input type="text" name="searchProductName" class="layui-input" placeholder="请输入产品名称">
                    </div>
                </div>
                <div class="layui-inline">
                    <label class="layui-form-label">客户名称</label>
                    <div class="layui-input-inline">
                        <input type="text" name="searchCustomerName" class="layui-input" placeholder="请输入客户名称">
                    </div>
                </div>
                <div class="layui-inline">
                    <button type="button" class="layui-btn" id="searchWorkOrderBtn">
                        <i class="layui-icon layui-icon-search"></i> 搜索
                    </button>
                    <button type="button" class="layui-btn layui-btn-primary" id="resetWorkOrderBtn">
                        <i class="layui-icon layui-icon-refresh"></i> 重置
                    </button>
                </div>
            </div>
        </div>
        <table id="workOrderTable" lay-filter="workOrderTable"></table>
    </div>

    <script src="~/scripts/jquery-3.4.1.min.js"></script>
    <script src="~/scripts/layui-v2.5.6/layui/layui.js"></script>
    <script>
        layui.use(['form', 'laydate', 'layer', 'table'], function(){
            var form = layui.form;
            var laydate = layui.laydate;
            var layer = layui.layer;
            var table = layui.table;
            
            // 初始化日期选择器
            laydate.render({
                elem: '#testingDate',
                type: 'datetime',
                format: 'yyyy-MM-dd HH:mm:ss'
            });
            
            // 监听自动生成开关
            form.on('switch(autoGenerate)', function(data){
                var $processCode = $('input[name="ProcessCode"]');
                if(data.elem.checked) {
                    // 选中自动生成时
                    $processCode.prop('readonly', true).addClass('layui-disabled');
                    generateProcessCode($processCode);
                } else {
                    // 取消自动生成时
                    $processCode.prop('readonly', false).removeClass('layui-disabled').val('');
                }
            });
            
            // 监听表单提交
            form.on('submit(submitForm)', function(data){
                var loadIndex = layer.load(2, {
                    shade: [0.3, '#000']
                });
                
                // 获取防伪令牌
                var token = $('input[name="__RequestVerificationToken"]').val();
                
                // 发送AJAX请求
                $.ajax({
                    url: '/Process/AddProcess',
                    type: 'POST',
                    data: JSON.stringify(data.field),
                    contentType: 'application/json; charset=utf-8',
                    headers: {
                        'RequestVerificationToken': token
                    },
                    success: function(result) {
                        layer.close(loadIndex);
                        if(result === 1) {
                            layer.msg('添加成功！', {
                                icon: 1,
                                time: 1000
                            }, function(){
                                // 跳转到显示页面
                                window.location.href = '/Process/Getproce';
                            });
                        } else {
                            layer.msg('添加失败，请重试！', {icon: 2});
                        }
                    },
                    error: function(xhr, status, error) {
                        layer.close(loadIndex);
                        console.error('Error:', xhr);
                        layer.msg('添加失败：' + (xhr.responseJSON ? xhr.responseJSON.message : '服务器错误'), {icon: 2});
                    }
                });
                
                return false; // 阻止表单跳转
            });
            
            // 表单验证规则
            form.verify({
                number: function(value) {
                    if(value && !/^\d+$/.test(value)) {
                        return '请输入有效的数字';
                    }
                }
            });

            // 添加一个按钮来填充测试数据
            $('<button type="button" class="layui-btn layui-btn-normal" style="margin-left: 10px;" id="fillTestData">填充测试数据</button>')
                .insertAfter('button[type="reset"]');
            
            // 填充测试数据功能
            $('#fillTestData').click(function() {
                fillTestData();
            });

            // 绑定工作站选择按钮点击事件
            $(document).on('click', '.select-work-station-btn', function() {
                selectWorkStation();
            });
        });
        
        // 选择工作站功能（全局函数）
        function selectWorkStation() {
            layui.use(['layer', 'table', 'form'], function() {
                var layer = layui.layer;
                var table = layui.table;
                var form = layui.form;
                
                console.log('开始显示工作站选择弹出框');
                
                // 打开弹出框
                var layerIndex = layer.open({
                    type: 1,
                    title: '工作站选择',
                    area: ['1200px', '600px'],
                    content: $('#workStationDialog'),
                    success: function(layero, index) {
                        console.log('工作站弹出框打开成功，开始初始化表格');
                        
                        // 重新渲染表单元素
                        form.render();
                        
                        // 初始化表格
                        var tableIns = table.render({
                            elem: '#workStationTable',
                            url: '/Process/GetWorkStationList',
                            method: 'get',
                            page: true,
                            limit: 10,
                            cols: [[
                                {type: 'radio', width: 50},
                                {field: 'workStationCode', title: '工作站编号', width: 120},
                                {field: 'workStationName', title: '工作站名称', width: 180},
                                {field: 'processBelongs', title: '所属工序', width: 150},
                                {field: 'workshop', title: '所在车间', width: 120},
                                {field: 'capacity', title: '备注', width: 150}
                            ]],
                            parseData: function(res) {
                                console.log('工作站数据响应:', res);
                                return {
                                    "code": res.code || 0,
                                    "msg": res.msg || "",
                                    "count": res.count || 0,
                                    "data": res.data || []
                                };
                            },
                            done: function(res, curr, count) {
                                console.log('工作站表格渲染完成:', res, '当前页:', curr, '总数:', count);
                            }
                        });

                        // 监听行选择事件
                        table.on('radio(workStationTable)', function(obj) {
                            console.log('选中工作站:', obj.data);
                            var data = obj.data;
                            
                            // 填充表单数据
                            $('input[name="WorkStationCode"]').val(data.workStationCode || '');
                            $('input[name="WorkStationName"]').val(data.workStationName || '');
                            
                            // 关闭弹出框
                            layer.close(layerIndex);
                            
                            // 显示成功消息
                            layer.msg('工作站选择成功', {icon: 1});
                        });

                        // 搜索按钮事件
                        $('#searchWorkStationBtn').off('click').on('click', function() {
                            console.log('执行工作站搜索');
                            var searchData = {
                                workStationCode: $('input[name="searchWorkStationCode"]').val(),
                                processBelongs: $('input[name="searchProcessBelongs"]').val(),
                                workshop: $('input[name="searchWorkshop"]').val()
                            };
                            console.log('工作站搜索条件:', searchData);
                            
                            // 重新加载表格
                            table.reload('workStationTable', {
                                where: searchData,
                                page: {
                                    curr: 1
                                }
                            });
                        });

                        // 重置按钮事件
                        $('#resetWorkStationBtn').off('click').on('click', function() {
                            console.log('重置工作站搜索条件');
                            $('#workStationDialog input[type="text"]').val('');
                            form.render('select');
                            
                            // 重新加载表格
                            table.reload('workStationTable', {
                                where: {},
                                page: {
                                    curr: 1
                                }
                            });
                        });
                    }
                });
            });
        }
        
        // 生成检验单编号函数
        function generateProcessCode($input) {
            // 生成规则：PC + 年月日 + 4位序号
            var date = new Date();
            var year = date.getFullYear();
            var month = (date.getMonth() + 1).toString().padStart(2, '0');
            var day = date.getDate().toString().padStart(2, '0');
            
            // 这里应该调用后端接口获取序号，这里暂时模拟
            var sequence = Math.floor(Math.random() * 9999).toString().padStart(4, '0');
            
            var code = 'PC' + year + month + day + sequence;
            $input.val(code);
        }
        
        // 填充测试数据函数
        function fillTestData() {
            layui.use(['form'], function() {
                var form = layui.form;
                
                // 填充测试数据
                $('input[name="ProcessCode"]').val('PC20250125001');
                $('select[name="ProcessType"]').val('过程检验');
                $('input[name="OrderCode"]').val('MO20250620250002');
                $('input[name="WorkStationCode"]').val('005');
                $('input[name="WorkStationName"]').val('贴标与包装工位');
                $('input[name="ProductCode"]').val('CP00025');
                $('input[name="ProductName"]').val('A套餐');
                $('input[name="Specifications"]').val('300*120');
                $('input[name="Unitt"]').val('PCS');
                $('input[name="TestingNum"]').val('10');
                $('input[name="TestingDate"]').val('2025-01-25 14:30:00');
                $('select[name="TestingResult"]').val('合格');
                $('input[name="TestingPerson"]').val('张三');
                $('select[name="State"]').val('1');
                
                // 重新渲染表单
                form.render();
                
                // 显示成功消息
                layer.msg('测试数据填充完成', {icon: 1});
            });
        }
        
        // 选择工单功能
        function selectWorkOrder() {
            layui.use(['layer', 'table'], function() {
                var layer = layui.layer;
                var table = layui.table;
                
                console.log('开始显示工单选择弹出框');
                
                // 打开弹出框
                var layerIndex = layer.open({
                    type: 1,
                    title: '选择工单',
                    area: ['1200px', '600px'],
                    content: $('#workOrderDialog'),
                    success: function(layero, index) {
                        console.log('弹出框打开成功，开始初始化表格');
                        
                        // 初始化表格
                        var tableIns = table.render({
                            elem: '#workOrderTable',
                            url: '/Process/GetProductionWorkOrderList',
                            method: 'get',
                            page: true,
                            limit: 10,
                            cols: [[
                                {type: 'radio', width: 50},
                                {field: 'workOrderCode', title: '工单编码', width: 160},
                                {field: 'workOrderName', title: '工单名称', width: 200},
                                {field: 'productCode', title: '产品编号', width: 120},
                                {field: 'productName', title: '产品名称', width: 200},
                                {field: 'productModel', title: '规格型号', width: 120},
                                {field: 'unit', title: '单位', width: 80},
                                {field: 'workOrderQuantity', title: '工单数量', width: 100},
                                {field: 'customerName', title: '客户名称', width: 160}
                            ]],
                            parseData: function(res) {
                                console.log('工单数据响应:', res);
                                return {
                                    "code": res.code || 0,
                                    "msg": res.msg || "",
                                    "count": res.count || 0,
                                    "data": res.data || []
                                };
                            },
                            done: function(res, curr, count) {
                                console.log('工单表格渲染完成:', res, '当前页:', curr, '总数:', count);
                            }
                        });

                        // 监听行选择事件
                        table.on('radio(workOrderTable)', function(obj) {
                            console.log('选中工单:', obj.data);
                            var data = obj.data;
                            
                            // 填充表单数据
                            $('input[name="OrderCode"]').val(data.workOrderCode || '');
                            $('input[name="ProductCode"]').val(data.productCode || '');
                            $('input[name="ProductName"]').val(data.productName || '');
                            $('input[name="Specifications"]').val(data.productModel || '');
                            $('input[name="Unitt"]').val(data.unit || '');
                            
                            // 关闭弹出框
                            layer.close(layerIndex);
                            
                            // 显示成功消息
                            layer.msg('工单选择成功', {icon: 1});
                        });

                        // 搜索按钮事件
                        $('#searchWorkOrderBtn').off('click').on('click', function() {
                            console.log('执行搜索');
                            var searchData = {
                                workOrderCode: $('input[name="searchWorkOrderCode"]').val(),
                                workOrderName: $('input[name="searchWorkOrderName"]').val(),
                                productCode: $('input[name="searchProductCode"]').val(),
                                productName: $('input[name="searchProductName"]').val(),
                                customerName: $('input[name="searchCustomerName"]').val()
                            };
                            console.log('搜索条件:', searchData);
                            
                            // 重新加载表格
                            table.reload('workOrderTable', {
                                where: searchData,
                                page: {
                                    curr: 1
                                }
                            });
                        });

                        // 重置按钮事件
                        $('#resetWorkOrderBtn').off('click').on('click', function() {
                            console.log('重置搜索条件');
                            $('#workOrderDialog input[type="text"]').val('');
                            
                            // 重新加载表格
                            table.reload('workOrderTable', {
                                where: {},
                                page: {
                                    curr: 1
                                }
                            });
                        });
                    }
                });
            });
        }
    </script>
</body>
</html>
